<template>
  <section>
    <el-row>
      <el-col :span="24">
        <!--顶部操作按钮-->
        <el-space class="top-btns">
          <el-dropdown split-button type="primary" size="small" @click="loadData(true, true)">导出
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-button type="primary" size="small" @click="loadData(true)">勾选导出</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button type="info" size="small" @click="handleEdit({})">添加</el-button>
          <el-button type="success" size="small" @click="onSubmit">刷新</el-button>
        </el-space>

        <!--搜索表单-->
        <el-form :inline="true" size="small">
          <el-form-item label="标题">
            <el-input v-model="criteria.title" placeholder="标题"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="vip">
            <el-select v-model="criteria.type" placeholder="请选择" clearable>
              <el-option v-for="(item,key) in typeList" :key="key" :label="item.name" :value="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button type="primary" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
        <!--数据表格-->
        <el-table :data="tableData" border size="small" @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center" width="40"/>
          <el-table-column prop="type_name" label="类型" align="center"></el-table-column>
          <el-table-column prop="title" label="标题" align="center"></el-table-column>
          <el-table-column label="图片" align="center">
            <template #default="scope">
              <el-image style="width: 80px; height: 80px" :src="scope.row.image" :preview-src-list="[scope.row.image]" fit="contain" preview-teleported hide-on-click-modal />
            </template>
          </el-table-column>
          <el-table-column prop="url" label="跳转路由" align="center"></el-table-column>
          <el-table-column label="状态" align="center">
            <template #default="scope">
              <el-switch :model-value="scope.row.status ? true : false"
                         @change="changeStatus($event, scope.$index, scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" align="center"></el-table-column>
          <el-table-column prop="update_at" label="更新时间" align="center"></el-table-column>
          <el-table-column prop="create_at" label="添加时间" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" @click="handleEdit(scope.row)" size="small"><el-icon><EditPen/></el-icon></el-button>
              <el-button type="danger" @click="handleDelete(scope.row)" size="small"><el-icon><Delete/></el-icon></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination background @current-change="handleCurrentChange" @size-change="handleSizeChange"
                         :current-page="page" :page-size="pageSize"
                         :page-sizes="[20, 50, 100, 200, 1000]"
                         layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog :title="dialogTitle" center v-model="dialogFormVisible">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类型" prop="level">
          <el-select v-model="form.type" placeholder="请选择" clearable>
            <el-option v-for="(item,key) in typeList" :key="key" :label="item.name" :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload :show-file-list="false"
                     class="avatar-uploader"
                     :action="$Api.uploadUrl()"
                     :on-success="imageSuccess"
                     :on-remove="imageRemove"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div style="color: red;margin-left: 20px">{{px_text}}</div>
        </el-form-item>
        <el-form-item label="跳转路由" prop="url">
          <el-input v-model="form.url"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSave" :loading="editLoading">保存</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </section>
</template>
<script setup>
  import { ref,computed } from "vue";
  import { ElMessage,ElMessageBox } from 'element-plus'
  import func from '@/common/func'
  const criteria = ref({})
  const tableData = ref([])
  const typeList = ref([])
  const dialogFormVisible = ref(false)
  const dialogTitle = ref('')
  const editLoading = ref(false)
  const formRef = ref(null)
  const form = ref({})
  const rules = ref({
    title: [{required: true, message: '请输入标题', trigger: 'blur'}],
    image: [{required: true, message: '请输入图片', trigger: 'change'}],
  })
  const page = ref(1)
  const pageSize = ref(20)
  const totalCount = ref(0)
  let criteria_default = {}
  let ids = []
  let listUrl = '/banner/bannerList'
  let editUrl = '/banner/bannerEdit'
  let deleteUrl = '/banner/bannerDel'
  let setStatusUrl = '/banner/bannerEditStatus'

  for (let i in criteria.value) {
    if (criteria_default[i] === undefined) {
      criteria_default[i] = criteria.value[i];
    }
  }
  loadData();

  const px_text = computed(()=>{
    let px = ''
    for (let i=0; i < typeList.value.length; i++) {
      if (form.value.type == typeList.value[i].key) {
        px = typeList.value[i].px
        break
      }
    }
    return px
  })

  function onSubmit() {
    if (page.value !== 1) {
      page.value = 1;
    }
    loadData();
  }
  function onReset() {
    for (var i in criteria.value) {
      criteria.value[i] = criteria_default[i];
    }
  }
  function changeStatus(status, index, row) {
    func.request(setStatusUrl, {id: row.id, status: status ? 1 : 0}).then(res => {
      if (res.code === 1) {
        row.status = status
        tableData.value[index] = row
      }
    });
  }
  function handleDelete(row) {
    ElMessageBox.confirm('确认删除吗？', '提示').then(() => {
      func.request(deleteUrl, {id: row.id}).then(res => {
        if (res.code === 1) {
          ElMessage({message: res.msg,type: 'success'})
          loadData()
        }
      });
    }).catch(()=>{})
  }
  function handleEdit(row) {
    if (row.id) {
      dialogTitle.value = '编辑'
      form.value = {
        id: row.id,
        type: row.type,
        title: row.title,
        image: row.image,
        url: row.url,
        sort: row.sort,
      }
    } else {
      dialogTitle.value = '添加'
      form.value = {}
    }
    dialogFormVisible.value = true
  }
  function handleSave() {
    formRef.value.validate((valid) => {
      if (!valid) {
        return false
      }
      editLoading.value = true;
      func.request(editUrl, form.value).then(res => {
        editLoading.value = false;
        if (res.code === 1) {
          ElMessage({message: res.msg,type: 'success'})
          loadData()
          dialogFormVisible.value = false
        }
      });
    });
  }
  function handleCurrentChange(val) {
    if (page.value !== val) {
      page.value = val;
    }
    loadData();
  }
  function handleSizeChange(val) {
    if (pageSize.value !== val) {
      pageSize.value = val;
      loadData();
    }
  }
  function handleSelectionChange(v) {
    let r = []
    for (let item of v) {
      r.push(item.id)
    }
    ids = r
  }
  function loadData(is_export=false,all=false) {
    var pdt = {};
    if (undefined !== criteria.value) {
      pdt = JSON.parse(JSON.stringify(criteria.value));
    }
    pdt.page = page.value;
    pdt.pageSize = pageSize.value;
    if (is_export) {
      pdt.export = 1
      if (all) {
        pdt.page = 1;
        pdt.pageSize = 100000;
      } else {
        if (ids.length === 0) {
          ElMessage({message:'请选择要操作的数据',type: 'error'})
          return
        }
        pdt.ids = ids.join(',')
      }
    }
    func.request(listUrl, pdt).then(res => {
      if (res.code === 1) {
        if (is_export) {
          window.open(res.data.url)
          return
        }
        tableData.value = res.data.list;
        totalCount.value = res.data.total;
        typeList.value = res.data.typeList;
      }
    });
  }

  function imageRemove() {
    form.value.image = ''
  }
  function imageSuccess(response) {
    if (response.code === 1) {
      form.value.image = response.data.url
    }
  }
</script>

<style scoped lang="scss">
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  width: 300px;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  .avatar {
    max-width: 100%;
    max-height: 100%;
    display: block;
  }
}
</style>

